package com.bowen.spike.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;

import cn.hutool.jwt.JWTUtil;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


public class JwtUtil {

    // JWT 密钥
    private static final String SECRET_KEY;
    // 解析失败结果
    public static final long PARSING_FAILED = -1;

    static {
        try (InputStream inputStream = JwtUtil.class.getClassLoader().getResourceAsStream("application.yaml")) {
            if (inputStream == null) {
                throw new RuntimeException("无法找到配置文件 application.yaml");
            }
            Yaml yaml = new Yaml();
            Map<String, Object> config = yaml.load(inputStream);
            SECRET_KEY = (String) (((LinkedHashMap<?, ?>) (config.get("secret"))).get("key"));
            if (SECRET_KEY == null || StrUtil.isBlank(SECRET_KEY)) {
                throw new IllegalStateException("SECRET_KEY 未正确初始化，请检查配置文件");
            }
        } catch (Exception e) {
            throw new RuntimeException("无法加载配置文件", e);
        }
    }
    /**
     * 生成 JWT Token
     *
     * @param userId 用户 ID
     * @return JWT Token
     */
    public static String getToken(Long userId) {
        Map<String, Object> payload = new HashMap<>();
        payload.put("userId", userId);
        // 为了方便，设置过期时间为7天
        long expiresAt = System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000;
        payload.put(JWTPayload.EXPIRES_AT, expiresAt);

        return JWTUtil.createToken(payload, SECRET_KEY.getBytes());
    }
    /**
     * 解析 JWT Token
     *
     * @param token JWT Token
     * @return 载荷信息
     */
    public static long parseToken(String token) {
        try {
            return JWTUtil.parseToken(token).getPayloads().getLong("userId");
        } catch (Exception e) {
            e.printStackTrace();
            return PARSING_FAILED;
        }
    }

}
